package com.kgc.kmall.kmallorderservice.service.impl;

import com.kgc.kmall.bean.Order;
import com.kgc.kmall.bean.OrderExample;
import com.kgc.kmall.bean.OrderItem;
import com.kgc.kmall.kmallorderservice.mapper.OrderItemMapper;
import com.kgc.kmall.kmallorderservice.mapper.OrderMapper;
import com.kgc.kmall.service.OrderService;
import com.kgc.kmall.util.RedisUtil;
import org.apache.dubbo.config.annotation.Service;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service
@Component
public class OrderServiceImpl implements OrderService {
    @Resource
    OrderMapper orderMapper;
    @Resource
    RedisUtil redisUtil;
    @Resource
    OrderItemMapper orderItemMapper;


    @Override
    public String genTradeCode(Long memberId) {
        Jedis jedis = redisUtil.getJedis();

        String tradeKey = "user:"+memberId+":tradeCode";

        String tradeCode = UUID.randomUUID().toString();
        System.out.println("生成TradeCode:"+tradeCode);

        jedis.setex(tradeKey,60*15,tradeCode);

        jedis.close();

        return tradeCode;
    }

    @Override
    public String checkTradeCode(Long memberId, String tradeCode) {
        Jedis jedis = redisUtil.getJedis();

        String key = "user:"+memberId+":tradeCode";

        String value=jedis.get(key);
        System.out.println("查验code,传入:"+value);
        //删除code
        jedis.del(key);
        if (StringUtils.isNotBlank(tradeCode)&&StringUtils.isNotBlank(value)&&tradeCode.equals(value)){
            jedis.close();
            System.out.println("code查验成功");
            return "success";
        }
        System.out.println("code查验失败");
        jedis.close();

        return "fail";
    }

    @Override
    public void saveOrder(Order omsOrder) {
        orderMapper.insertSelective(omsOrder);
        for (OrderItem orderItem : omsOrder.getOrderItems() ) {
            orderItem.setOrderId(omsOrder.getId());

            orderItemMapper.insertSelective(orderItem);
        }
    }

    @Override
    public Order getOrderByOutTradeNo(String outTradeNo) {
        OrderExample example=new OrderExample();
        example.createCriteria().andOrderSnEqualTo(outTradeNo);
        List<Order> orders = orderMapper.selectByExample(example);
        if (orders!=null&&orders.size()>0){
            return orders.get(0);
        }else{
            return null;
        }
    }

    @Override
    public void updateOrder(Order omsOrder) {
            OrderExample example=new OrderExample();
            example.createCriteria().andOrderSnEqualTo(omsOrder.getOrderSn());
        omsOrder.setStatus(1);
        orderMapper.updateByExampleSelective(omsOrder,example);
    }
}
